package com.jinyang.plugindemo.contentprovider

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.jinyang.plugindemo.log

class StubContentProvider : ContentProvider() {

    private var pluginProvider: ContentProvider? = null
    private var uriMatcher: UriMatcher? = UriMatcher(UriMatcher.NO_MATCH)


    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        log("StubContentProvider.insert")
        return loadPluginProvider()?.insert(uri, values)
    }


    override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
        log("StubContentProvider.query: uri=$uri")
        if (isPlugin1(uri)) {
            return loadPluginProvider()?.query(uri, projection, selection, selectionArgs, sortOrder)
        }
        return null
    }

    override fun onCreate(): Boolean {
        log("StubContentProvider.onCreate")
        uriMatcher?.addURI("com.ljy.StubContentProvider", "plugin001", 1)
        uriMatcher?.addURI("com.ljy.StubContentProvider", "plugin002", 2)
        return true
    }

    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
        log("StubContentProvider.update")
        return loadPluginProvider()?.update(uri, values, selection, selectionArgs) ?: 0
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        log("StubContentProvider.delete")
        return loadPluginProvider()?.delete(uri, selection, selectionArgs) ?: 0
    }

    override fun getType(uri: Uri): String {
        log("StubContentProvider.getType")
        return loadPluginProvider()?.getType(uri) ?: ""
    }

    private fun loadPluginProvider(): ContentProvider? {
        if (pluginProvider == null) {
            pluginProvider = PluginUtils.classLoader?.loadClass("com.jinyang.plugin001.PluginContentProvider")?.newInstance() as ContentProvider?
        }
        return pluginProvider
    }

    private fun isPlugin1(uri: Uri?): Boolean {
        log("StubContentProvider.isPlugin1:${uriMatcher?.match(uri)}")
        if (uriMatcher?.match(uri) == 1) {
            return true
        }
        return false
    }
}

class PluginUtils {
    companion object {
        var classLoader: ClassLoader? = null
    }
}